<template>
  <div class="app">
    <div class="detail-container">
      <Notice></Notice>
      <div class="content">
        <div class="titleTag">{{ detailTitle }}</div>
        <basicForm
          ref="formDetailRef"
          :info="routeQuery"
          @getPaiqianList="getPaiqianList"
        />
      </div>
      <div class="content mt10" v-if="paiqianList.length > 0">
        <div class="titleTag">派遣信息</div>
        <a-spin :spinning="paiqianLoading || deptLoading || userLoading" tip="正在加载信息...">
          <div
            class="equal-division-container"
            v-for="item in paiqianList"
            :key="item.id"
          >
            <div class="equal-division-item">派遣ID：{{ item.pqId }}</div>
            <div class="equal-division-item">派遣类型：{{ getPqType(item.pqType,'dispatchTypeList') }}</div>
            <div class="equal-division-item">派遣状态：{{ getPqType(item.pqStatus,'dealStatusList') }}</div>
            <div class="equal-division-item">
              部门名称：{{ deptInfoMap[item.processDeptId] && deptInfoMap[item.processDeptId].deptName }}
            </div>
            <div class="equal-division-item">
              负责人名称：{{ userInfoMap[item.processDeptUserId] && userInfoMap[item.processDeptUserId].userName }}
            </div>
            <div class="equal-division-item">
              处理人名称：{{ userInfoMap[item.processUserId] && userInfoMap[item.processUserId].userName }}
            </div>
            <div class="equal-division-item">更新时间：{{ item.updateTime }}</div>
            <div class="equal-division-item">
              案件受理驳回理由：{{ item.deptRefuseDesc }}
            </div>
            <div class="equal-division-item">
              案件审核驳回理由：{{ item.centerRefuseDeptDesc }}
            </div>
            <div class="equal-division-item">
              <span >处理结果描述：{{ item.processDesc }}</span>
              <span 
                class="file-link" 
                v-if="item.processUrl"
                @click="() => previewImage(item.processUrl)"
              >
                <a-icon :type="getFileIconType(item.processUrl)" style="margin-right: 5px;" />
                附件：{{ getFileName(item.processUrl) }}
              </span>
            </div>
          </div>
        </a-spin>
      </div>
      <div class="content mt10" v-if="routeQuery.type !== 'wdsb'">
        <div class="titleTag">事件进展</div>
        <CaseProgress />
      </div>
      <CommonOperation
        :info="routeQuery"
        @submit="handleDeal"
        @edit="handleEdit"
      />
      <a-modal :title="modalInfo.title" :visible="modalInfo.visible" @cancel="handleModalCancel">
        <component
          :is="`${routeQuery.pageType}Dialog`"
          ref="formDialogRef"
          :info="modalInfo"
        />
        <template slot="footer">
          <a-button key="back" @click="handleModalCancel"> 取消 </a-button>
          <a-button
            key="submit"
            type="primary"
            :loading="submitLoading"
            @click="handleModalOk"
          >
            确定
          </a-button>
        </template>
      </a-modal>
    </div>
  </div>
</template>
<script>
import CaseProgress from "./CaseProgress.vue";
import CommonOperation from "./commonOperation.vue";
import dictMixin from "@/mixins/dictMixin";
import Notice from "@/component/notice.vue";

export default {
  name: "WdsbIndex",
  mixins: [dictMixin],
  components: {
    CaseProgress,
    CommonOperation,
    Notice,
    basicForm: () => import("./basicForm.vue"),
    jxhpqDialog: () => import("./jxhpqDialog.vue"),
    ajslDialog: () => import("./ajslDialog.vue"),
    wdpqdDialog: () => import("./wdpqdDialog.vue"),
    pqdshDialog: () => import("./pqdshDialog.vue"),
    ajshDialog: () => import("./ajshDialog.vue"),
  },
  data() {
    return {
      roadList: [],
      routeQuery: {
        isEdit: true,
        buttonObj: {},
      },
      modalInfo: {
        visible: false,
        title: "",
        type: "",
      },
      submitLoading: false,
      paiqianList: [],
      paiqianLoading: false,
      deptLoading: false,  // 部门信息加载状态
      userLoading: false,  // 用户信息加载状态
      // 用于存储部门和用户信息的对象
      deptInfoMap: {},  // key是部门ID，值是部门信息
      userInfoMap: {},   // key是用户ID，值是用户信息
      // ----------------------------信息
      currentIndex: 0,
      itemHeight: 40, // 单个项的高度（需与 CSS 一致）
      offsetindex: 0,
      timer: null,
      msgList:[],

      // ------------------------------------信息
    };
  },
  computed: {
    detailTitle() {
      const { operationType, pageType } = this.routeQuery;
      switch (pageType) {
        case "wdsb":
          return operationType === "Report" ? "事件上报" : "案件详情";
        case "jxhpq":
          return "案件详情";
        case "ajsl":
          return "案件受理";
        case "wdpqd":
          return "我的派遣单";
        case "pqdsh":
          return "派遣审核";
        case "ajsh":
          return "案件审核";
        case "ajgd":
          return "案件归档";
        case "wdrw":
          return "待办案件详情";
        default:
          return "案件详情";
      }
    },
  },

  methods: {
    getPqType(val,type) {
      let findOne = this[type].find(
        (item) => item.value == val
      );
      return (findOne && findOne.label) || "";
    },
    getPaiqianList(val) {
      this.paiqianList = val || [];
    },
    // 判断是否为图片文件
    isImageFile(url) {
      if (!url) return false;
      return /\.(png|jpg|jpeg|gif|bmp)$/i.test(url);
    },
    // 获取文件图标类型
    getFileIcon(fileName) {
      if (!fileName) return "file";

      const ext = fileName.split(".").pop().toLowerCase();
      const iconMap = {
        pdf: "file-pdf",
        doc: "file-word",
        docx: "file-word",
        xls: "file-excel",
        xlsx: "file-excel",
        ppt: "file-ppt",
        pptx: "file-ppt",
        txt: "file-text",
        jpg: "picture",
        jpeg: "picture",
        png: "picture",
        gif: "picture",
      };

      return iconMap[ext] || "file";
    },
    // 获取文件图标类型（用于展示）
    getFileIconType(url) {
      if (!url) return "file";
      
      const fileName = this.getFileName(url);
      const ext = fileName.split(".").pop().toLowerCase();
      
      const iconMap = {
        pdf: "file-pdf",
        doc: "file-word",
        docx: "file-word",
        xls: "file-excel",
        xlsx: "file-excel",
        ppt: "file-ppt",
        pptx: "file-ppt",
        txt: "file-text",
        jpg: "picture",
        jpeg: "picture",
        png: "picture",
        gif: "picture",
        zip: "file-zip",
        rar: "file-zip",
      };
      
      return iconMap[ext] || "file";
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return "";
      return url.split("/").pop();
    },
    // 预览图片和文件
    previewImage(url) {
      if (!url) {
        this.$message.warning('没有可预览的文件');
        return;
      }
      
      if (this.isImageFile(url)) {
        // 如果是图片类型，可以尝试使用预览组件(如果存在)
        if (this.$preview && typeof this.$preview.open === 'function') {
          this.$preview.open({
            src: url,
            downloadable: true,
          });
        } else {
          // 否则直接在新窗口打开
          window.open(url, '_blank');
        }
      } else {
        // 非图片文件直接在新窗口打开
        window.open(url, '_blank');
      }
    },
    // 筛选值
    formatData(data) {
      // 过滤掉值为 undefined 和 null 的属性
      data = Object.fromEntries(
        Object.entries(data).filter(
          ([_, value]) => value !== undefined && value !== null
        )
      );
      return data;
    },
    // 公共提交部分
    async commonSubmit(targetData, path) {
      // 将对象转换为 URLSearchParams 格式
      const params = new FormData();
      for (const key in targetData) {
        params.append(key, targetData[key]);
      }
      this.submitLoading = true;
      await this.$axios
        .post(`/government-platform-center/case/${path}`, params, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          if (res.data.code === 0) {
            this.$message.success("提交成功");
            // 提交成功后返回上一页
            this.$router.back();
          }
        })
        .catch((err) => {
          this.$message.error("提交失败，请稍后重试");
        })
        .finally(() => {
          this.submitLoading = false;
        });
    },
    // 获取按钮权限
    getButton(val) {
      // 将对象转换为 URLSearchParams 格式
      const params = new URLSearchParams();
      params.append("eventId", val.id);

      this.$axios
        .post("/government-platform-center/case/getCaseDetailButton", params)
        .then((res) => {
          if (res.data.code === 0) {
            this.routeQuery.buttonObj = res.data.data;
            if(this.routeQuery.pageType == 'wdrw'){ // 我的待办，可以办理什么案件取决于用户是什么角色
              let btnData = res.data.data;
                // <!-- 我的上报 -->
                if(btnData.bianji || btnData.zancun || btnData.shangbao || btnData.zhijiebanjie){
                  this.routeQuery.pageType = 'wdsb';
                }
                else if(btnData.userqueren || btnData.userbanjie || btnData.userfangongqueren){
                  this.routeQuery.pageType = 'jxhpq';
                }
                else if(btnData.deptshoulitongguo || btnData.deptshoulibohui){
                  this.routeQuery.pageType = 'ajsl';
                }
                else if(btnData.userqueren || btnData.userbanjie || btnData.userfangongqueren){
                  this.routeQuery.pageType = 'wdpqd';
                }
                else if(btnData.deptshenhetongguo || btnData.deptshenhebohui){
                  this.routeQuery.pageType = 'pqdsh';
                }
                else if(btnData.anjianshenhetongguo || btnData.anjianshenhebohui){
                  this.routeQuery.pageType = 'ajsh';
                }
                else if(btnData.guidang){
                  this.routeQuery.pageType = 'ajgd';
                }




            }
            
          }
        });
    },
    // 弹窗提交
    handleModalOk() {
      switch (this.routeQuery.pageType) {
        case "jxhpq":
          this.handleDispatchSubmit();
          break;
        case "ajsl":
          this.handleAcceptSubmit();
          break;
        case "wdpqd":
          this.handleConfirmSubmit();
          break;
        case "pqdsh":
          this.handleAuthSubmit();
          break;
        case "ajsh":
          this.handleAuditSubmit();
          break;
      }
    },
    // 按钮操作处理
    async handleDeal(data) {
      switch (this.routeQuery.pageType) {
        case "wdsb":
          this.handleReport(data);
          break;
        case "jxhpq":
          this.handleDispatch(data);
          break;
        case "ajsl":
          this.handleAccept(data);
          break;
        case "wdpqd":
          this.handleConfirm(data);
          break;
        case "pqdsh":
          this.handleAuth(data);
          break;
        case "ajsh":
          this.handleAudit(data);
          break;
        case "ajgd":
          this.handleArchive(data);
          break;
      }
    },
    // 关闭弹窗
    handleModalCancel() {
      this.modalInfo.visible = false;
    },
    // 我的上报
    async handleReport(data) {
      let formData = await this.$refs.formDetailRef.getFormValues();
      console.log(formData, "formData");
      let targetData = {
        ...this.formatData(formData),
        ...data,
        eventId: this.routeQuery.id,
      };
      const {relatedObjectData,...rest} = targetData
      let path = this.routeQuery.isEdit ? "addCase" : "updateCase";
      this.commonSubmit(rest, path);
    },
    // 我的上报编辑
    handleEdit() {
      this.routeQuery.isEdit = false;
    },
    // 精细化派遣
    handleDispatch(data) {
      this.modalInfo.visible = true;
      this.modalInfo.title = "精细化派遣";
    },
    /**
     * 从对象中提取所有以指定前缀开头且以数字结尾的键对应的值,并用逗号连接
     * @param {Object} obj - 要处理的对象
     * @param {String} prefix - 键的前缀
     * @return {String} - 逗号连接的值字符串
     */
    getFieldValuesByPrefix(obj, prefix) {
      const regex = new RegExp(`^${prefix}\\d+$`);

      const values = Object.keys(obj)
        .filter((key) => regex.test(key))
        .map((key) => obj[key]);

      return values.join(",");
    },
    // 精细化派遣提交
    async handleDispatchSubmit(data) {
      let formData = await this.$refs.formDialogRef.getFormValues();
      let targetData = {
        ...this.formatData(formData),
        eventId: this.routeQuery.id,
      };
      let muiltDepartmentId = "";
      // 多部门派遣
      if (targetData.pqType === "6") {
        muiltDepartmentId = this.getFieldValuesByPrefix(
          formData,
          "muiltDepartmentId"
        );
        targetData = {
          ...targetData,
          muiltDepartmentId,
        };
      }
      // 双派遣
      if (targetData.pqType === "7") {
        muiltDepartmentId = this.getFieldValuesByPrefix(
          formData,
          "doubleDepartmentId"
        );
        targetData = {
          ...targetData,
          muiltDepartmentId,
        };
      }
      if (targetData.pqType === "8") {
        targetData = {
          ...targetData,
          muiltDepartmentId: `${targetData.mianDepartmentId},${targetData.secondDepartmentId}`,
        };
      }
      this.commonSubmit(targetData, "paiQian");
    },

    // 案件受理
    handleAccept(data) {
      this.modalInfo = {
        visible: true,
        title: "案件受理",
        type: data,
      };
    },
    // 案件受理提交
    async handleAcceptSubmit(data) {
      let formData = await this.$refs.formDialogRef.getFormValues();
      let targetData = {
        ...this.formatData(formData),
        pqId: this.routeQuery.paramId,
      };
      let path =
        this.modalInfo.type === "Accept" ? "paiQianAccept" : "paiQianRefuse";
      this.commonSubmit(targetData, path);
    },

    // 我的派遣单-确认派遣
    handleConfirm(data) {
      if (data === "End") {
        this.modalInfo = {
          visible: true,
          title: "派遣办结",
          type: data,
        };
      } else {
        // 确认派遣
        let targetData = {
          pqId: this.routeQuery.paramId,
        };
        this.commonSubmit(targetData, "confirmPaiqian");
      }
    },
    // 我的派遣单-派遣办结
    async handleConfirmSubmit(data) {
      let formData = await this.$refs.formDialogRef.getFormValues();
      let targetData = {
        ...this.formatData(formData),
        pqId: this.routeQuery.paramId,
      };
      this.commonSubmit(targetData, "commitPaiqian");
    },

    // 派遣单审核
    handleAuth(data) {
      if (data === "Reject") {
        this.modalInfo = {
          visible: true,
          title: "派遣审核",
          type: data,
        };
      } else {
        // 审核驳回
        let targetData = {
          pqId: this.routeQuery.paramId,
        };
        this.commonSubmit(targetData, "confirmPaiqianToExamine");
      }
    },
    // 派遣单审核---审核通过提交
    async handleAuthSubmit() {
      let formData = await this.$refs.formDialogRef.getFormValues();
      let targetData = {
        ...this.formatData(formData),
        pqId: this.routeQuery.paramId,
      };
      this.commonSubmit(targetData, "refusePaiqianToExamine");
    },

    // 案件审核
    handleAudit(data) {
      if (data === "Reject") {
        this.modalInfo = {
          visible: true,
          title: "案件审核驳回",
          type: data,
        };
      } else {
        let targetData = {
          eventId: this.routeQuery.id,
          status: "51", //结案
        };
        this.commonSubmit(targetData, "examineCaseSuccess");
      }
    },
    // 案件审核提交
    async handleAuditSubmit() {
      let formData = await this.$refs.formDialogRef.getFormValues();
      let targetData = {
        ...this.formatData(formData),
        eventId: this.routeQuery.id,
      };
      this.commonSubmit(targetData, "examineCaseRefuse");
    },
    // 案件归档
    handleArchive() {
      let targetData = {
        eventId: this.routeQuery.id,
        status: "6", //归档
      };
      this.commonSubmit(targetData, "examineCaseSuccess");
    },
    // 提取并去重ID字段
    getUniqueIds(list) {
      if (!list || list.length === 0) return { processDeptIds: [], processDeptUserIds: [], processUserIds: [] };
      
      // 使用对象映射进行一次性去重
      const deptIdMap = {};
      const deptUserIdMap = {};
      const userIdMap = {};
      
      // 一次遍历列表，提取所有ID
      list.forEach(item => {
        // 处理部门ID
        if (item.processDeptId) {
          deptIdMap[item.processDeptId] = true;
        }
        
        // 处理部门用户ID
        if (item.processDeptUserId) {
          deptUserIdMap[item.processDeptUserId] = true;
          // 将部门用户ID也加入到用户ID映射中
          userIdMap[item.processDeptUserId] = true;
        }
        
        // 处理处理人ID
        if (item.processUserId) {
          userIdMap[item.processUserId] = true;
        }
      });
      
      // 从映射对象获取唯一ID数组
      const processDeptIds = Object.keys(deptIdMap);
      const processDeptUserIds = Object.keys(deptUserIdMap);
      const processUserIds = Object.keys(userIdMap);
      
      // 输出日志
      console.log('去重后的部门ID:', processDeptIds);
      console.log('去重后的部门用户ID:', processDeptUserIds);
      console.log('去重后的处理人ID:', processUserIds);
      
      return {
        processDeptIds,
        processDeptUserIds,
        processUserIds
      };
    },
    // 处理去重后的ID
    handleUniqueIds(uniqueIds) {
      const { processDeptIds, processDeptUserIds, processUserIds } = uniqueIds;
      
      // 记录处理的开始时间，用于性能监控
      const startTime = Date.now();
      
      // 获取部门信息并存储到deptInfoMap中
      if (processDeptIds.length > 0) {
        this.deptLoading = true;  // 开始加载部门信息，设置loading状态
        processDeptIds.forEach(id => {
          // 如果deptInfoMap中已有该ID的数据，则跳过
          if (!this.deptInfoMap[id]) {
            this.getDeptInfo(id);
          }
        });
        console.log('部门信息Map:', this.deptInfoMap);
      }
      
      // 获取用户信息并存储到userInfoMap中
      if (processUserIds.length > 0) {
        this.userLoading = true;  // 开始加载用户信息，设置loading状态
        processUserIds.forEach(id => {
          // 如果userInfoMap中已有该ID的数据，则跳过
          if (!this.userInfoMap[id]) {
            this.getUserInfo(id);
          }
        });
        console.log('用户信息Map:', this.userInfoMap);
      }
      
      // 记录处理消耗的时间
      console.log('ID处理耗时:', Date.now() - startTime, 'ms');
      
      return {
        success: true,
        message: '处理成功',
        data: uniqueIds,
        deptInfoMap: this.deptInfoMap,
        userInfoMap: this.userInfoMap
      };
    },
    
    // 获取部门信息
    getDeptInfo(deptId) {
      // 这里假设调用API获取部门信息
      const params = new URLSearchParams();
      params.append("deptId", deptId);
      
      this.$axios
        .get(`/government-platform-center/dept/${deptId}`)
        .then(res => {
          if (res.data.code === 0) {
            // 将API返回的数据保存到deptInfoMap中，以deptId为key
            this.$set(this.deptInfoMap, deptId, res.data.data);
          }
        })
        .catch(err => {
          console.error('获取部门信息失败:', err);
          // 即使失败也设置一个值，避免重复请求
          this.$set(this.deptInfoMap, deptId, { error: true });
        })
        .finally(() => {
          // 检查是否所有部门信息都已加载完毕
          const allDeptLoaded = this.paiqianList.every(item => 
            !item.processDeptId || this.deptInfoMap[item.processDeptId]
          );
          if (allDeptLoaded) {
            this.deptLoading = false;  // 关闭部门loading状态
          }
        });
    },
    
    // 获取用户信息
    getUserInfo(userId) {
      // // 这里假设调用API获取用户信息
      const params = new URLSearchParams();
      params.append("userId", Number(userId));
      
      this.$axios
        .get("/government-platform-center/user/getUserInfo", {
          params: params
        })
        .then(res => {
          if (res.data.code === 0) {
            // 将API返回的数据保存到userInfoMap中，以userId为key
            this.$set(this.userInfoMap, userId, res.data.data);
          }
        })
        .catch(err => {
          console.error('获取用户信息失败:', err);
          // 即使失败也设置一个值，避免重复请求
          this.$set(this.userInfoMap, userId, { error: true });
        })
        .finally(() => {
          // 检查是否所有用户信息都已加载完毕
          const allUserLoaded = this.paiqianList.every(item => 
            (!item.processDeptUserId || this.userInfoMap[item.processDeptUserId]) &&
            (!item.processUserId || this.userInfoMap[item.processUserId])
          );
          if (allUserLoaded) {
            this.userLoading = false;  // 关闭用户loading状态
          }
        });
    },
    startScroll() {
      this.timer = setInterval(() => {
        // 计算下一个索引
        this.currentIndex = (this.currentIndex + 1) % this.msgList.length;
        // 更新偏移量
        this.offsetindex = -this.currentIndex * this.itemHeight;
      }, 2000); // 2秒切换一次
    },
    stopScroll() {
      clearInterval(this.timer);
    },
    getmsgList() {
     
      const url = "/government-platform-center/leader/getPublicMsg";
      this.$axios
        .post(url, {
            current: 40,
            offset: 1,
            isRead: 0,
          }, 
          {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          
          if (res.data.code == 0 && res.data.data.length > 0 ) {
            console.log('消息消息=====',res.data.data)
            res.data.data.map(v=>{
              this.msgList.push(v.title)
            })
            this.startScroll();

          }
        });
    },
    handTap(type){
      // this.$emit('jumpTo', type);
       this.$router.push({
        path: type
      });

    },
  },

  created() {
    // 获取路由 query 参数
    this.routeQuery = {
      ...this.routeQuery,
      ...this.$route.query,
    };
    // this.getmsgList();
  },
  watch: {
    "$route.query": {
      handler(val) {
        if (val.id && val.pageType !== "ajgz") {
          this.getButton(val);
        }
      },
      immediate: true,
      deep: true,
    },
    paiqianList: {
      handler(val) {
        // 确保有数据时才处理
        if (val && val.length > 0) {
          // 提取三种ID并去重
          const uniqueIds = this.getUniqueIds(val);
          
          // 处理去重后的IDs
          this.handleUniqueIds(uniqueIds);
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.detail-container {
  width: 100%;
  overflow-y: auto;
  // height: calc(100vh - 90px);
}
.header {
  height: 40px;
  line-height: 40px;
  background: #fff;
  padding: 0 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 10px;
}
.left {
  flex-shrink: 0;
  width: auto;
}
.right {
  flex: 1;
  min-width: 0;
}
.content {
  padding: 10px;
  background: #fff;
  border-radius: 5px;
  height: fit-content;
  .titleTag {
    // margin-left: 10px;
    // color: #4285f4;
    font-size: 18px;
    font-weight: 500;
    margin: 10px 0;
    // color: #4285f4;
  }
}
.full-width-textarea {
  width: 100%;
  display: block;
}

.equal-division-container {
  display: flex;
  flex-wrap: wrap;
  margin: 10px 0;
  width: 100%;
  border-bottom: 1px solid #e8e8e8;
}

.equal-division-item {
  width: calc(20% - 10px);
  box-sizing: border-box;
  height: fit-content;
  margin: 5px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  text-align: left;
  padding: 10px;
  min-height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-link {
  color: #4285f4; 
  margin-left: 10px; 
  max-width: 120px; 
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: nowrap; 
  cursor: pointer; 
  display: inline-block;
}

.file-link:hover {
  text-decoration: underline;
  opacity: 0.8;
}

:deep(.ant-input) {
  width: 100%;
}

.scroll-container {
  height: 40px; /* 显示区域高度 */
  overflow: hidden;
  cursor: pointer;
}
.scroll-content {
  transition: transform 0.50s ease; /* 平滑过渡动画 */
}
.item {
  height: 40px;
  line-height: 40px;
  text-align: left;
  display: flex;
  align-items: center;
}
.item img{
  width: 20px;
  height: 20px;
  // margin-right: 10px;
}
</style>
